import urllib.request

import urllib.parse

import json

continues = ''

while continues != 'n':


    c2e = input('输入要翻译的内容：')

    #传入urllib.request.urlopen需要的url和data参数

    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=https://www.baidu.com/link'
    # 传入User-Agent对象，将python的请求伪装成浏览器的请求 这里是第一种方法
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER'
    data = {}
    data['type'] = 'AUTO'
    data['i'] = c2e
    data['doctype'] = 'json'
    data['xmlVersion'] = '1.8'
    data['keyfrom'] = 'fanyi.web'
    data['ue'] = 'UTF-8'
    data['action'] = 'FY_BY_CLICKBUTTON'
    data['typoResult'] = 'true'

    data = urllib.parse.urlencode(data).encode('utf-8') #将utf-8格式的内容转换为python和服务器需要的格式

    req = urllib.request.Request(url,data,head)
    response = urllib.request.urlopen(req)

    html = response.read().decode('utf-8') #将response.read读取的内容反编译为utf-8格式

    target = json.loads(html)

    print('翻译结果为;"%s"' % target['translateResult'][0][0]['tgt'])

   # continues = input('是否还翻译其他内容？按任意键继续，输入n结束：')
    
    #if continues  == 'n':
        #print('感谢您的使用，再见~')
